/* ----------------------------------------------------------------------------
* File: base_module.cpp
*
* Desc: Base module for Skype plugin
*
* Created: 12/08/2011, by Alexey Korshunov
* ---------------------------------------------------------------------------- */
#include "base_module.h"
#include "debug_logger.h"

namespace ModuleManagement
{
	BaseModule::BaseModule(const std::string& name, const ModuleType& type) 
		throw(Common::Exception)
		: Name(name)
		, Type(type)
		, ID(0)
	{
		m_Logger = Common::CreateDebugLogger();
		if (!m_Logger.get())
			throw Common::Exception(Name + ": " + "ERROR - Unable to create default logger");
	}

	BaseModule::~BaseModule()
	{
		Stop();
	}

	Common::Error BaseModule::Start()
	{
		if (StartThread())
		{
			std::string str = Name + ": START";
			m_Logger->Print(str.c_str());
			return Common::SKYPE_SUCCESS;
		}
		return Common::SKYPE_ERROR;
	}

	Common::Error BaseModule::Stop()
	{
		StopThread();
		std::string str = Name + ": STOP";
		m_Logger->Print(str.c_str());
		return Common::SKYPE_SUCCESS;
	}

	Common::Error BaseModule::WaitStop()
	{
		WaitThread();
		std::string str = Name + ": STOP";
		m_Logger->Print(str.c_str());
		return Common::SKYPE_SUCCESS;
	}

	ModuleType BaseModule::GetType() const
	{
		return Type;
	}

	unsigned int BaseModule::GetID() const
	{
		return ID;
	}

	void BaseModule::SetID(unsigned int id)
	{
		ID = id;
	}

	Common::Error BaseModule::Run()
	{
		Common::Error err = BeforeRun();
		if (err != Common::SKYPE_SUCCESS)
			return err;

		try
		{
			RunLogic();
		}
		catch(const Common::Exception& ex)
		{
			std::string str = Name + ": EXCEPTION - %s";
			m_Logger->Print(str.c_str(), ex.GetStr().c_str());
		}
		catch(...)
		{
			std::string str = Name + ": EXCEPTION - Unexpected";
			m_Logger->Print(str.c_str());
		}

		return AfterRun();
	}
}